# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000000
HISTFILESIZE=2000000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar

# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm-color) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#finalx ++
force_color_prompt=yes
#finalx --

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
	# We have color support; assume it's compliant with Ecma-48
	# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
	# a case would tend to support setf rather than setaf.)
	color_prompt=yes
    else
	color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    #finalx ++
    #PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
    #PS1='${debian_chroot:+($debian_chroot)}\[\033[01;$((30+$RANDOM%7))m\]\u@\t\[\033[00m\] \[\033[01;33m\]\w>\[\033[00m\]\$ '
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;30m\]\u@\t\[\033[00m\] \[\033[01;33m\]\w>\[\033[00m\]\$ '
    #finalx --
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
    ;;
*)
    ;;
esac

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
    alias ls='ls --color=auto'
    #alias dir='dir --color=auto'
    #alias vdir='vdir --color=auto'

    alias grep='grep --color=auto'
    alias fgrep='fgrep --color=auto'
    alias egrep='egrep --color=auto'
fi

# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

# Add an "alert" alias for long running commands.  Use like so:
#   sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
    . /etc/bash_completion
fi

export ANDROID_NDK=$MYBIN/android-ndk-r9d
export ANDROID_SDK_HOME=$HOME/android-sdk-linux
mkdir -p /tmp/logs

function lutong (){
    echo lutong0321@192.168.65.17
}
export -f lutong

getFileRelateToTop ()
{
    fileAbsDir=$(cd $(dirname $1 ) && pwd);
    fileRelateToTop=$(cd $fileAbsDir && echo ${fileAbsDir#$(get_android_top.sh)}/$(basename $1));
    echo $fileRelateToTop | sed 's/^\/*//g'
}

mymeld ()
{
    target=$(getFileRelateToTop $1);
    meld ${kk_shinano}/$target $aosp/$target
}

myvimdiff ()
{
    target=$(getFileRelateToTop $1);
    vimdiff ${kk_shinano}/$target $aosp/$target
}

vimat ()
{
    vim `echo "$1" | sed -r 's/:([0-9]+).*/ \+\1/'`
}

function n() {
    tempfile=$(mktemp)
    start_secs=$(date +%s)
    wd=$(pwd)
    eval "$*" 2>&1 | tee $tempfile
    end_secs=$(date +%s)
    notify-send "$wd ~> $*: using $(($end_secs - $start_secs)) s :" "$(tail $tempfile)"
    rm $tempfile
    echo -e "\\033[41;37m[ $(($end_secs - $start_secs))s ]: $wd ~> $*\\033[0m"
}
export -f n

function now() {
    date +%Y%m%d_%H%M%S
}
export -f now

function dumpsf {
    adb shell dumpsys SurfaceFlinger
}
export -f dumpsf

function on_watch_changed() {

    dump_dest=$1
    #dumping files may not completed when /data/sfdump* is exist on device
    #adb pull /data/$last_new $dump_dest/$last_new
    echo -e "\n\\033[41;37madb pull /data/$last_new $dump_dest/$last_new \\033[0m"
}

function watch_dumped_file() {
    watch_count=0
    dump_count=$1;  shift
    last_old=$1;    shift
    dump_type=$1;   shift
    call_back=$1;   shift
    dump_dest=$1;   shift

    while [ $watch_count -le $(($dump_count * 60)) ]; do
        last_new=$(adb shell ls data | grep "^sfdump\.$dump_type" | tail -1 | tr -d '\r')

        if [ "$last_old" != "$last_new" ] ; then
            $call_back $dump_dest
            break
        fi

        last_old=$last_new
        ((watch_count ++))
        sleep 1
    done
}

function dump_internal() {
    dump_cmd=$1
    dump_type=$2
    dump_count=$3

    dump_dest=/tmp/logs/dump_$(date +%Y%m%d_%H%M%S).$(date +%N | cut -c -3)
    mkdir -p $dump_dest/dumpsurfaces
    mkdir -p $dump_dest/dumpwindows

    #myloop0 "dumpsurface > $dump_dest/dumpsurfaces/dumpsurface.\$myloop0_count"

    dumpsf > $dump_dest/dumpsurface.txt
    echo -e "\\033[41;37m$dump_dest/dumpsurface.txt \\033[0m"
    #dumpwindow > $dump_dest/dumpwindow.txt
    #echo -e "\\033[41;37m$dump_dest/dumpwindow.txt \\033[0m"

    [ -z $dump_count ] && return

    current_key=$([ "$dump_type" == "raw" ] && echo "\[debug.sf.dump\]" || ([ "$dump_type" == "png" ] && echo "\[debug.sf.dump.png\]"))
    current_value=$(adb shell getprop | grep "$current_key" | awk -F"\[|\]" '{print $4}')
    [ -z "$current_value" ] && current_value=0

    if [ "$current_value" -eq "$dump_count" ]; then
        echo "$current_key already set to $current_value, try $((current_value + 1))"
        ((dump_count ++))
    fi

    last=$(adb shell ls data | grep "^sfdump\.$dump_type" | tail -1 | tr -d '\r')

    echo "adb shell $dump_cmd $dump_count"
set -x
    if adb shell $dump_cmd $dump_count ; then
        watch_dumped_file "$dump_count" "$last" "$dump_type" "on_watch_changed" "$dump_dest"
    fi
set -
}

alias dumppng='dump_internal "setprop debug.sf.dump.png" png'
alias dumpraw='dump_internal "setprop debug.sf.dump" raw'

function repo() {
    echo -e "[START] `now`\t`pwd`\t$*" >> ~/.repo.logs
    $(which repo) $*
    echo -e "[STOP ] `now`\t`pwd`\t$*\t[$?]\n" >> ~/.repo.logs
}
export -f repo

function initrepo() {
    new_repo=$1
    set -x
    mkdir -p $new_repo
    cd $new_repo
    repo init -u git://review.sonyericsson.net/platform/manifest --repo-url=git://review.sonyericsson.net/tools/repo -b $new_repo
    set -
}
export -f initrepo

function pushrepo() {
    set -x
    git push ssh://lu.x.tong@review.sonyericsson.net:29418/${1} HEAD:refs/changes/${2}
    set -
}

function adbkill() {
    psinfo=$(mktemp)
    adb shell ps | grep $1 | tee $psinfo
    [ $(wc -l $psinfo | awk '{print $1}') -ne 1 ] && echo "no/too many matches" && return
    adb shell kill $(awk '{print $2}' $psinfo)
    rm -f $psinfo
}

function raw_file_name_to_imagemagick_option() {
    local afile=$1
    local arr_fields=($(echo "$(basename $afile .raw)" | sed 's/\./ /g'))
    [ ${#arr_fields[*]} -ne 5 ] && return

    local dumpid=${arr_fields[0]}
    local layerid=${arr_fields[1]}
    local size=${arr_fields[2]}
    local colorspace=$(echo ${arr_fields[3]} | awk -F_ '{print $1}')
    local depth=8 #$(echo ${arr_fields[3]} | awk -F_ '{print $2}' | cut -c 1)
    ###primary=${arr_fields[5]}
    [ -z "$dumpid" ] && return
    [ -z "$layerid" ] && return
    [ -z "$size" ] && return
    [ -z "$colorspace" ] && return
    [ -z "$depth" ] && return

    if [ $colorspace == "RGBX" -o $colorspace == "RGB" ]; then colorspace="RGBA"; fi

    echo "-depth $depth -size $size $colorspace:$afile"

}

function display_raw_loop() {
    local afile=$1
    local opt_str=$(raw_file_name_to_imagemagick_option $afile)
    [ -z "$opt_str" ] && return

    echo "display $opt_str"
    display $opt_str
}

function rawdisplay() {
    for iFile in $*; do
        display_raw_loop "$iFile"
    done
}

function convert_raw_loop() {

    local src_file=$1
    local dest_file=$2
    local opt_str=$(raw_file_name_to_imagemagick_option $src_file)

    if [ -z "$opt_str" ]; then
        echo "Convert $src_file Error !!!"
        return
    fi

    echo "convert $opt_str --> $dest_file"
    convert $opt_str $dest_file
}

function rawconvert() {
    if mkdir -p rawconvert_png; then

        local max_bgs=8
        local iCount=0

        (for iFile in $*; do

            convert_raw_loop $iFile "rawconvert_png/$(basename $iFile .raw).png" &
            ((iCount ++))

            if [ $iCount -ge $max_bgs ]; then
                wait
                iCount=0
            fi

        done #iFile
        wait) 2> /dev/null

    fi #mkdir
}

function myloop1() {
    loopcount=0
    while true; do
        eval "$*"
        echo "loopcount = $loopcount"

        ((loopcount++))
        sleep 1
    done
}

function myloop0() {
    loopcount=0
    loopcount4="0000"

    while true; do
        eval "$*"
        loopcount4=$(echo $loopcount | awk '{printf("%04d",$0)}')
        echo "loopcount4 = $loopcount4"
        ((loopcount++))
    done
}

function tailog() {
	tail $* ~/logs/other/mvAccordingSwLable.sh.log
}

function adbpushrun {
    adb root && adb wait-for-device && sleep 1 && adb remount && adb wait-for-device
    adb shell mkdir -p /data/local/tmp
    adb push $1 /data/local/tmp
    adb shell chmod -R 777 /data/local/tmp
    adb shell /data/local/tmp/$(basename $1)
}

function mmvim {
    cd /proc/$(ps -ef | grep vim | grep -v 'grep' | awk '{print $2}')/cwd
    set -x
    cd $(pwd -P)
    set -
    mymmpush $*
}

alias cd2='cd ../../'
alias cd3='cd ../../../'
alias cd4='cd ../../../../'
alias cd5='cd ../../../../../'
alias njvpn2='echo njvpn2@192.168.65.42'
alias yutao0909='echo yutao0909@192.168.65.15'
alias yutao='echo yutao0909@192.168.65.217'
alias jinxin='echo jinxin@192.168.65.48'
alias jinxin0102='echo jinxin0102@192.168.65.16'
alias liuyang='echo liuyang@192.168.65.32'
alias MM='echo mm@192.168.65.70'
alias ZAG='echo zhaoanguo@192.168.64.40'

alias adbwait='adb wait-for-device'
alias dumpenable='adbwait; adb root; adbwait; adb shell setenforce 0; adb shell setprop debug.sf.dump.enable true; adb shell setprop debug.sf.dump.external true'
alias dumpdisable='adbwait; adb root; adbwait; adb shell setprop debug.sf.dump.enable false'
alias dumpwindow='adb shell dumpsys window'
alias adbmediascan='set -x; adb shell pm clear com.sonyericsson.album; adb shell am broadcast -a android.intent.action.MEDIA_MOUNTED -d file:///mnt/sdcard; set -'
alias nows='date +%s'
alias routeadd='set -x; sudo route add -net 0.0.0.0 netmask 0.0.0.0 gw 192.168.65.1; set -'
alias routedel='sudo route del -net 0.0.0.0 netmask 0.0.0.0 gw 192.168.65.1'
alias pjson='python -c "import sys, json; print json.dumps(json.load(sys.stdin), sort_keys=True, indent=4)"'

function foregroundActChange {
    old=""
    ADB="adb"

    while true; do
        new=$($ADB shell dumpsys activity activities | grep mFocusedActivity | awk '{print $4}')
        if [ "$old" != "$new" ]; then
            echo "$(now)    $new"
        fi
        old=$new
        sleep 0.1
    done
}
export -f foregroundActChange

function __gerrit_reviewer_internal {
    if [ $# -lt 3 ]; then
        return
    fi
    echo $*

    local gerrit_repo=$1
    local added_reviewers=""
    for reviewer in ${@:2:$(($#-2))}; do
        added_reviewers="${added_reviewers} -a $reviewer"
    done
    local gerrit_id=${@:$#}

    set -x
    ssh -p 29418 lu.x.tong@review.sonyericsson.net gerrit set-reviewers --project $gerrit_repo ${added_reviewers} $gerrit_id
    set -
}

function gerrit_reviewer_ts {
    if [ $# -ne 2 ]; then
        return
    fi
    #gerrit_reviewer_internal `git config -l | grep project | cut -d'=' -f2` \
    __gerrit_reviewer_internal $1 \
        yang.xa.liu@sonymobile.com  \
        lina.x.pi@sonymobile.com    \
        zhen.x.chen@sonymobile.com  \
        $2
}

function gerrit_reviewer_somc {
    if [ $# -ne 2 ]; then
        return
    fi
    #gerrit_reviewer_internal `git config -l | grep project | cut -d'=' -f2` \
    __gerrit_reviewer_internal $1 \
        yoshinori.ito@sonymobile.com    \
        masanori.igarashi@sonymobile.com    \
        huaming.wang@sonymobile.com     \
        takahiro.aizawa@sonymobile.com  \
        tomohiro.arikado@sonymobile.com \
        ryo.x.sakuma@sonymobile.com     \
        $2
}

function get_prop {
    FILE_PROP=$1
    [ -z "$FILE_PROP" ] && return
    cat $FILE_PROP | grep "\[$2\]" | awk -F"[\[\]]" '{print $(NF-1)}'
}

function mytrace {
    dur=$1

    TMPFILE_PROP=$(mktemp)
    adb shell getprop > $TMPFILE_PROP
    build_product=$(get_prop $TMPFILE_PROP "ro.build.product")
    build_id=$(get_prop $TMPFILE_PROP "ro.build.id")
    build_type=$(get_prop $TMPFILE_PROP "ro.build.type")
    android_serial="$ANDROID_SERIAL"
    if [ -z "$android_serial" ]; then
        android_serial=$(get_prop $TMPFILE_PROP "ro.serialno")
    fi
    rm -f $TMPFILE_PROP

    now=$(date +%Y%m%d_%H%M%S).$(date +%N | cut -c -3)
    output="/tmp/logs/systrace.${now}-${build_product}-${build_id}-${build_type}-${android_serial}-${dur}s.html"

    $ANDROID_SDK_HOME/platform-tools/systrace/systrace.py \
        --time=${dur} sched gfx view wm input am hal freq sync \
        -o $output
}
export -f mytrace


export PATH=$PATH:$projects/semc_tools/tools/swe-utils:$MYBIN:$MYBIN/common_shell_scripts:/opt/ftp-server/install:$ANDROID_NDK:$HOME/shared_build_server/lutong0321/projects/l-mr1-kitakami2/build/tools:$HOME/projects/l-shinano/build/tools

# deqp ++
alias deqpAndroidServer='set -x; adb forward tcp:50016 tcp:50016; adb shell setprop log.tag.dEQP DEBUG; adb shell am start -n com.drawelements.deqp.execserver/.ServiceStarter; set -'
#alias deqpAndroidActivity='set -x; adb shell am start -n com.drawelements.deqp.execserver/android.app.NativeActivity \
#    -e cmdLine "deqp --deqp-case=dEQP-GLES2.info.* --deqp-log-filename=/sdcard/dEQP-Log.qpa --deqp-surface-width=0 --deqp-surface-height=0"; set -'
export deqpAndroidExecutorArg='--connect=127.0.0.1 --port=50016 --binaryname=com.drawelements.deqp.execserver/android.app.NativeActivity --caselistdir=/home/finalx/Documents/dEQP-2014.2.3-2014-09-05-Sony/Candy/Data --testset=dEQP-GLES3.* --out=BatchResult.qpa --cmdline="--deqp-crashhandler=enable --deqp-watchdog=enable --deqp-gl-config-name=rgba8888d24s8 --deqp-surface-width=0 --deqp-surface-height=0"'
#deqp --

#export JAVA_HOME=/usr/java/jdk1.6.0_35
export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-amd64
export HISTTIMEFORMAT="%Y/%m/%d/%T "
export GRAPHICS_OUT_DIR=/home/finalx/test_resources/gat/GRAPHICS_OUT_DIR
export GRAPHICS_OUT_PATH=/home/finalx/test_resources/gat/GRAPHICS_OUT_PATH

#DMS
alias clearMascot='adb shell pm clear com.nttdocomo.android.mascot'
function killmediaserver {
    adb shell ps | grep mediaserver
    adb shell kill $(adb shell ps | grep /system/bin/mediaserver | awk '{print $2}')
    adb shell ps | grep mediaserver
}
